<template>
  <div class='roles'>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 顶部按钮 -->
      <el-row class="addButton">
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="rolesList"
        border
        style="width: 100%"
      >
        <el-table-column type="expand">
          <!-- 对应的权限 -->
          <template slot-scope="props">
            <el-row
              v-for="(firstAuth,index) in props.row.children"
              :key="firstAuth.id"
              :class="['authColBottom','vcAlign',index==0?'authColTop':'' ]"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="handleClose(props.row,firstAuth.id)"
                  class='authTag'
                  type='primary'
                >
                  {{firstAuth.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row
                  v-for="(secondAuth,index) in firstAuth.children"
                  :key="secondAuth.id"
                  :class="[index==0?'':'authColTop','vcAlign']"
                >
                  <el-col :span="12">
                    <el-tag
                      closable
                      @close="handleClose(props.row,secondAuth.id)"
                      class='authTag'
                      type='success'
                    >
                      {{secondAuth.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="12">
                    <el-tag
                      closable
                      @close="handleClose(props.row,thirdAuth.id)"
                      class='authTag'
                      type='warning'
                      v-for="(thirdAuth,index) in secondAuth.children"
                      :key="thirdAuth.id"
                    >
                      {{thirdAuth.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          label="#"
          type="index"
          width="50"
        >

        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="level"
          label="操作"
        >
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑用户"
              placement="top-start"
              :enterable='false'
            >
              <el-button
                class="el-icon-edit"
                type="primary"
                size='mini'
                @click="editUser(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top-start"
              :enterable='false'
            >
              <el-button
                class="el-icon-delete"
                type="danger"
                size='mini'
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top-start"
              :enterable='false'
            >
              <el-button
                class="el-icon-setting"
                type="warning"
                size='mini'
                @click="editUserAuth(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>
    </el-card>
    <!-- 编辑用户权限弹出框 -->
    <el-dialog
      title="编辑用户权限"
      :visible.sync="editdialogVisible"
     
      width="60%"
    >
      <el-tree
        :data="userRightsList"
        show-checkbox
        node-key='id'
        :props="defaultProps"
        default-expand-all
        :default-checked-keys='defaultCheckedKeys'
        ref="treeAuth"
      >

      </el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editdialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmChange"
        >确定</el-button>
      </span>
    </el-dialog>

    <el-dialog
  title="修改角色"
  :visible.sync="editCharadialogVisible"
  width="50%"
  @close='resetUserInfo'
>
  <p>当前用户：{{userInfo.roleDesc}}</p>
  <p>当前角色：{{userInfo.roleName}}</p>
  分配新角色：<el-select v-model="selectedId"  placeholder="请选择">
     <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
    </el-option>
  </el-select>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">Cancel</el-button>
    <el-button type="primary" @click="confirmChangeName">Confirm</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  components: {},
  data() {
    return {
        //控制编辑用户权限弹出窗
      editdialogVisible: false,
      //控制编辑用户角色弹出窗
      editCharadialogVisible:false,
      //用户信息
      userInfo:{},
      //角色数组
      rolesList: [],
      userRightsList: [],
      defaultProps: {
        label: "authName",
        children: "children",
      },
      //默认的选中的权限
      defaultCheckedKeys:[],
        //选中的ID
        roleId:'',
        //选择组件中选择的ID
        selectedId:'',
    };
  },
  methods: {
      //刚开始加载时，就获取所有的角色数组，并渲染到组件中
    async getRolesList() {
      const { data: res } = await this.$http.get("/roles");

      if (res.meta.status === 200) {
        console.log("rolesList", res);
        this.rolesList = res.data;
        
      } else {
        console.log("fail");
      }
    },
    async handleClose(role, rightsId) {
      const res = await this.$confirm(
        "这将永久性删除，确定删除吗？",
        "删除权限",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res === "confirm") {
        const { data: deleteResult } = await this.$http.delete(
          `/roles/${role.id}/rights/${rightsId}`
        );
        if (deleteResult.meta.status !== 200) {
          return this.$message.error("删除权限失败已取消");
        }
        console.log("deleteResult", deleteResult);
        return (role.children = deleteResult.data);
      } else {
        return this.$message.info("删除操作已取消");
      }
    },

   async editUser(userInfo){
   
        this.userInfo=userInfo;
        this.editCharadialogVisible=true;
    },
    //获取到选择的id和当前的id发送到服务端进行更改
   async confirmChangeName(){
       if(!this.selectedId){
           return this.$message.error('请选择要更改的名字');
       }
       console.log('userInfo',this.selectedId);
       console.log('userInfo',this.userInfo);
       const {data:res}=await this.$http.put('/users/'+this.userInfo.id+'/role',{
           rid:this.selectedId
       })
       if(res.meta.status !== 200){
           return this.$message.error('更改失败');
       }
       this.$message.success('更改成功');
       this.getRolesList();
      return this.editCharadialogVisible=false;
    },
    //当关闭窗口时，重置selectedId，并刷新数据
    resetUserInfo(){
        this.selectedId='',
        this.getRolesList();
    },
    //*先获取所有的权限，渲染成权限树
    //*再对选择的用户权限渲染成chedked状态；
   async editUserAuth(role) {
       this.roleID=role.id;
       const {data:rightsList}=await this.$http.get('/rights/tree')
       if(rightsList.meta.status !==200) {
           return this.$message.error('获取权限数据失败')
       }
       this.userRightsList=rightsList.data;
    this.getDefaultCheckedKeys(role,this.defaultCheckedKeys)
    
      this.editdialogVisible = true;
 
    },
    
    //提交权限设置，需要先把半选和全选的权限拿到
   async confirmChange(){

        const checkedNodes=[
            ...this.$refs.treeAuth.getCheckedKeys(),
            ...this.$refs.treeAuth.getHalfCheckedKeys()
            ]
            const idStr=checkedNodes.join(",")
        const {data:res}=await this.$http.post(`/roles/${this.roleID}/rights`,{rids:idStr})

        if(res.meta.status !== 200){
            return this.$message.error('修改权限失败')
        }
        this.$message.success('success');
        this.editdialogVisible=false;
        return  this.getRolesList
  
    },

    //利用递归的算法把选中的用户id全部放到arr里面
    getDefaultCheckedKeys(role,arr){
        if(!role.children){
         return  arr.push(role.id);
        }
        role.children.forEach(e=>{
            this.getDefaultCheckedKeys(e,arr)
        });

    }
  },
  created() {
    this.getRolesList();
  },
};
</script>
<style lang='scss' scoped>
.el-card {
  margin-top: 20px;
  .addButton {
    margin-bottom: 10px;
  }
  .authTag {
    margin: 10px 0px;
  }
  .authColTop {
    border-top: 1px solid gray;
  }
  .authColBottom {
    border-bottom: 1px solid gray;
  }
  .vcAlign {
    display: flex;
    align-items: center;
  }
}
</style>